<?php
declare (strict_types=1);

namespace app\common\tool;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;

class Excel
{
    public function export($title, array $map, array $datas)
    {
        $file_name = $title . date('Y-m-d_His') . '.xls';
        $PHPExcel = new Spreadsheet();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle($title);
        $ordA = ord('A');
        $key2 = ord("@");
        foreach ($map as $k => $v) {
            if ($ordA > ord("Z")) {
                $colum = chr(ord("A")) . chr(++$key2);//超过26个字母 AA1,AB1,AC1,AD1...BA1,BB1...
            } else {
                $colum = chr($ordA++);
            }
            $index = $colum;
            $width = isset($v['width']) ? $v['width'] : 15;
            $PHPSheet->setCellValue($index . '1', $v['title'])->getColumnDimension($index)->setWidth($width);
        }

        $i = 2;
        foreach ($datas as $k => $v) {
            $ordA = ord('A');
            $key2 = ord("@");
            foreach ($map as $key => $val) {
                if ($ordA > ord("Z")) {
                    $colum = chr(ord("A")) . chr(++$key2);//超过26个字母 AA1,AB1,AC1,AD1...BA1,BB1...
                } else {
                    $colum = chr($ordA++);
                }
                $index = $colum;
                $PHPSheet->setCellValue($index . $i, $v[$val['key']]);
            }
            $i++;
        }
        $PHPWriter = new Xls($PHPExcel);
        header('Content-Disposition: attachment;filename=' . $file_name);
        ob_end_clean();
        $PHPWriter->save("php://output");
    }
}